<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/10/27
 * Time: 下午3:50
 */

namespace Admin\Mobile\Controllers;


use Admin\Models\bpm\XHBpmPlanContent;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\ims\XHImsApplyTablet;
use Admin\Models\ims\XHImsProdType;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\user\XhsysUser;
use Helpers\Assets;
use Helpers\Main;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Helpers\XhException;
use Admin\Models\lm\XHLmCar;
use Admin\Models\lm\XHLmUseCar;
use Modules\Ims;
use Modules\Power;

class BacklogController extends ControllerBase
{


    /**
     * 普通入口
     * created by dale 2017/10/26
     */
    public function nodeDetailAction()
    {

        Assets::easyUIMobile();
        $this->view->pick('backlog/nodeDetail');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/backlog/nodeDetail.js');
    }

    /**
     * 缴费入口
     * created by dale 2017/10/26
     */
    public function nodeFinanceAction(){
        Assets::easyUIMobile();
        $this->view->pick('backlog/nodeFinance');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/backlog/nodeFinance.js');
    }
    /**
     * 获取node详情
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/10/24
     */
    public function getNodeDetailAction()
    {
        $iBPCId = $this->request->getPost('iBPCId');
        $node = XHBpmPlanContent::findFirst([
            'conditions' => 'bDelete=0 AND iBPCId=:iBPCId:',
            'bind' => ['iBPCId' => $iBPCId],
        ])->toArray();
        return $this->sendJsonResponse($node);
    }

    public function getPlanAction()
    {
        $userId=Main::getLoginUserInfo('userId');
        $builder = $this->modelsManager->createBuilder()
            ->columns('pc.iBPCId,p.iBPPId,c.sSchoolName,pc.sNodeName,pc.tPlanDate,pc.iChargeId')
            ->from(['p' => 'Admin\Models\bpm\XHBpmPlan'])
            ->where('p.bDelete=0')
            ->leftJoin('Admin\Models\crm\XhcustInfo', 'c.iCUId=p.iCUId', 'c')
            ->leftJoin('Admin\Models\bpm\XHBpmPlanContent', 'pc.iBPPId=p.iBPPId AND pc.bDelete=0', 'pc')
            ->orderBy('p.tCreateDate,pc.iSort,pc.iBPCId')->andWhere('pc.tRealDate is null');

        if(Main::getLoginUserInfo('logonName')!='admin'){
            if(UserPower::checkUserPower('Bpm_Plan_Finance')){//如果有财务对接的权限
                $builder->andWhere('pc.iChargeId=:iChargeId: OR pc.sNodeName=:sNodeName:',array('iChargeId'=>$userId,'sNodeName'=>'缴费程序'));
            }else{
                $builder->andWhere('pc.iChargeId=:iChargeId:',array('iChargeId'=>$userId));
            }
        }
        $plans = $builder->getQuery()->execute()->toArray();
        foreach ($plans as $index => $row) {
            if (isset($row['tPlanDate']) && strtotime($row['tPlanDate']) < strtotime(date('Y-m-d', time()))) {
                $plans[$index]['color'] = 'red'; //红色
            } else {
                $plans[$index]['color'] = 'green';  //绿色
            }
        }
        return $plans;
    }

    public function getUseCarListAction(){
        $userId = Main::getLoginUserInfo('userId');
        $flag = !is_bool(strpos($this->changeToId(Main::getConfigByName('lm')['sOfficeCharges']),strval($userId)));
        if($flag){
            $sql ="select  iUCId,iDepId,iCreateUserId,iCarId from XHLm_UseCar WHERE (iState = 1 AND iChargeId = {$userId} ) OR iState = 2 AND bDelete =0 ";
        }else{
            $sql ="select  iUCId,iDepId,iCreateUserId,iCarId from XHLm_UseCar WHERE iState = 1 AND iChargeId = {$userId}  AND bDelete =0";
        }
        $useCars = $this->db->fetchAll($sql);
        if(count($useCars) <= 0){
            return [];
        }
        $deps = XhhrmDepart::getDepEnum();
        foreach ($useCars as $index=>$car){
            $useCars[$index]['sDepName'] = $deps[$car['iDepId']];
        }
        Main::runUserNameById($useCars, ['iCreateUserId'=>'userName'],true);
        return $useCars;
    }
    public static  $planReceiveType = [1 => '流程计划' , 2 => '学生机', 3 => '教师机', 4 =>'备用机', 5 => '公用机' , 6 => '自用机' ];
    /**
     * 获取设备领用
     * @return array
     * create by xjq 20180608
     */
    public function getTabletApplyAction(){
        if(Power::exist('Device_ApplyTab_Confirm')){
            $sql = "select * from  XHIms_ApplyTablet WHERE  bDelete = 0  and iState = 1 ";
            $data = $this->db->fetchAll($sql);
            $schools = XhschoolInfo::getSchoolArray();
            foreach ($data as &$row) {
                if ($row['iSchoolId']) {
                    $row['sSchoolName'] = $schools[$row['iSchoolId']];
                }
                $row['typeName'] = self::$planReceiveType[$row['iType']];
            }
        }else{
            $data = [];
        }
        return $data;
    }


    /**
     * 获取待办数目
     * @return string
     * created by dale 2017/10/27
     */
    public function getLogCountAction(){
        $this->view->disable();
        $count = 0;
        $count +=count($this->getPlanAction())+count($this->getUseCarListAction());
        if (Power::exist('Device_ApplyTab_Confirm')) {
            $count += count($this->getTabletApplyAction());
        }
        return json_encode(['count'=> $count]);
    }



    public function changeToId($str){
        $str=explode(',',$str);
        $users=XhsysUser::find([
            'columns'=>'iUserId',
            'conditions'=>'bDelete=0 AND sLogonName in ({ids:array})',
            'bind'=>['ids'=>$str]
        ])->toArray();

        $users=implode(',',array_column($users,'iUserId'));
        return $users;
    }




    /**
     * 初始化方法
     *
     * create by dale 2018/1/11
     */
    public function initAction()
    {
        $arr = [];
        $arr['plans']  = $this->getPlanAction();
        $arr['useCar'] = $this->getUseCarListAction();
        $arr['applyTab'] = $this->getTabletApplyAction();
        $arr['carRoute'] = $this->getCarRouteAction();
        return $this->sendJsonResponse($arr);
    }

    /**
     * 获取乘车列表
     *
     * @return array
     *
     * create by dale  20180910
     */
    public function getCarRouteAction()
    {
        $sql = "select * from XHLm_UseCar where sDriverName = '".Main::getLoginUserInfo('userName');
        $sql .= "' and iState = 3 and iCarId is not null and tEndTime >= '".date('Y-m-d H:i:s', time())."'";
        $carArr = $this->db->fetchAll($sql);
        return $carArr;
    }

    public function carDetailAction()
    {
        $iUCId = $this->request->getQuery('iUCId');
        Assets::easyUIMobile();
        $this->view->pick('backlog/carDetail');
        Assets::importJs('js/backlog/carDetail.js');
        $userId=Main::getLoginUserInfo('userId');
        $sql = "select * from XHLm_UseCar WHERE bDelete =0 AND iUCId = {$iUCId} ";
        $car = $this->db->fetchOne($sql);
        $car['sDepName'] = XhhrmDepart::getDepEnum()[$car['iDepId']];
        if ($car['iState'] == 0 && $car['iCreateUserId'] == $userId ) {
            $car['iState']=1;
        }else if ($car['iState'] == 1 && $car['iChargeId'] == $userId){ //部门审批阶段
            $chargeArr = $this->getChargeById($car['iCreateUserId'],true);
            if(end($chargeArr) == $userId){
                if(isset($car['iCarId'])){  //不是私家车
                    $car['iState'] = 2;
                }else{
                    $car['iState'] = 3;
                }

            }
        }else if($car['iState']==2) {
            $flag = !is_bool(strpos($this->changeToId(Main::getConfigByName('lm')['sOfficeCharges']), strval($userId)));
            if ($flag) {
                $car['iState'] = 3;
            }
        }
        if($car['iCarId']!=null){
            $sql = "select iCarId,sCarName,sPlateNum,iPersonNum from XHLm_Car WHERE iCarId ={$car['iCarId']}  ";
            $carInfo = $this->db->fetchOne($sql);
            $car['sCarName'] = $carInfo['sCarName'].'('.$carInfo['sPlateNum'].')限载'.$carInfo['iPersonNum'].'人';
        }
        $ids = explode(',',$car['sTravellers']);
        $staffs = XhhrmStaff::getStaffNameById($ids);
        foreach ($ids as $index => $id){
            $ids[$index] = $staffs[$id];
        }
        $car['sTravellers'] = implode(',',$ids);
        $hide = $this->request->getQuery('hideButton', 'string', null);
        if ($hide) {
            $this->view->setVar('hide', $hide);
        }
       $this->view->setVars([
           'car' => $car,

       ]);
    }

    public function getChargeById($userId,$isArr=false){
        $staff = XhhrmStaff::findFirst([
            'columns'    => 'iUserId,sDepIds',
            'conditions' => 'bDelete = 0 AND  iUserId = :iUserId:',
            'bind'       => ['iUserId' =>$userId]
        ]);
        $arr = [];
        $depIds = array_filter(explode(',',$staff->sDepIds));
        if(count($depIds) > 0){
            foreach ($depIds as $depId){
                $sql = "select iUserId from XHHrm_Staff  WHERE find_in_set('".$depId."',sChargeDeps) and bDelete = 0";
                $chargeId = $this->db->fetchOne($sql);
                if(isset($chargeId['iUserId'])){  //没有直接走上级的上级
                    $arr[] = $chargeId['iUserId'];
                }
            }
            if($arr[0] == $userId){
                unset($arr[0]);
            }
            $arr = array_values($arr);
            if($isArr){
                return $arr;
            }
            return implode(',',$arr);
        }
    }

    /**
     * 申请平板
     *
     * create by xjq 20180611
     */
    public function applyTabAction()
    {
        try {
            Assets::easyUIMobile();
            $type = $this->request->getQuery('type', 'int');
            $iRTId = $this->request->getQuery('iRTId', 'string');
            if (!$iRTId) {
                return $this->sendViewError('缺少参数');
            }
            $obj = XHImsApplyTablet::findFirst($iRTId);

            if (in_array($type, [1, 3])) {  // 流程计划 教师机
                $ids = explode(',', $obj->sTeachers);
                $teachers = [];
                foreach ($ids as $id) {
                    $teachers[] = ['id' => $id];
                }
                Main::runUserNameById($teachers, ['id' => 'name'], true);
                $teachers = array_column($teachers, 'name', 'id');
                $this->view->setVar('teachers', $teachers);
            }
            if ($type == 1) {
                $this->view->pick('backlog/applyTab');
                Assets::importJs('js/backlog/applyTab.js');
            } else if ($type == 3) {
                $this->view->pick('backlog/applyTab_tch');
                Assets::importJs('js/backlog/applyTab.js');
            }else if (in_array($type, [4, 5, 6])) { //备用 ，公用
                $this->view->pick('backlog/applyTab_back');
                Assets::importJs('js/backlog/applyTab_back.js');
            }
            $userName = XhsysUser::getUserNameById([$obj->iCreateUserId])[$obj->iCreateUserId];
            $this->view->setVar('user',$userName);
            $this->view->setVars([
                'iRTId' => $obj->iRTId,
                'iStuNum' => $obj->iStuNum,
                'iTchNum' => $obj->iTchNum,
                'prods' => Ims::getProdsByTypeName('平板'),
                'mode' => XhsysEnum::getEnumByNodeName('收费模式'),
                'tabletShell' => Ims::getProdsByTypeName('平板壳'),
                'type' => $type
            ]);
        } catch (XhException $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 确认申请_仅限流程计划 教师机
     *
     * create by xjq 20180611
     */
    public function confirmApplyAction(){
        $iRTId = $this->request->getPost('iRTId','int');
        $iProdId = $this->request->getPost('iProdId','int');
        $postData = $this->request->getPost();
        if (!$iRTId) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $obj = XHImsApplyTablet::findFirst($iRTId);
        $type = $obj->iType;
        if ($obj->iState ==2) {
            return $this->sendErrorResponse(500 , '该订单已经确认');
        }
        if ($type == 1 && !$iProdId) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        //教师平板的过滤
        $postData['tchCode'] = array_filter($postData['tchCode']);
        foreach ( $postData['tchCode'] as $index => $row) {
            if(!$row['code'] || !$row['iProdId']){
                unset($postData['tchCode'][$index]);
            }
        }
        $hasRepeatedTchCode = array_unique(array_column($postData['tchCode'] , 'code'));
        if(count($postData['tchCode']) !== count($hasRepeatedTchCode)){
            return $this->sendErrorResponse(400 ,'有重复的平板编号');
        }
        $hasRepeated = array_unique(array_column($postData['shellCode'] ,'prodId'));
        if (count($postData['shellCode']) !== count($hasRepeated)){
            return $this->sendErrorResponse(400 ,'有重复的平板壳');
        }
        foreach ($postData['shellCode'] as $index =>$row){
            if(!$row['prodId'] || !$row['iNum']){
                unset($postData['shellCode'][$index]);
            }
        }
        $postData['shellCode'] = array_values($postData['shellCode']);//过滤错误数据
        if (in_array($type, [1, 3])) {
            $obj->iProdId  = $iProdId;
            $obj->mTchCode = $postData['tchCode'];
            $obj->iStuNum  = $postData['iStuNum'];
            $obj->iTchNum  = count($postData['tchCode']);
            $obj->iChargeMode = $postData['iChargeMode'];
            $obj->sRealTch = implode(',' , array_keys($postData['tchCode']));
        } else if (in_array($type, [4, 5, 6])) {
            $obj->mTchCode = $postData['tchCode'];
            $obj->iTchNum  = count($postData['tchCode']);
        }
        $obj->mTabletShell = $postData['shellCode'];
        $obj->iState   = 2;
        if (!$obj->save()) {
            $this->sendErrorResponse(500 , '保存失败');
        }
        return $this->sendSuccessResponse('确认成功');
    }

    /**
     * 教师机跳过扫码入口
     *
     * create by dale  20180831
     */
    public function confirmTchBackAction(){
        try {
            $this->db->begin();
            $postData = $this->request->getPost();
            $iProdId = $this->request->getPost('iProdId','int');
            $iRTId = $this->request->getPost('iRTId','int');
            if (!$iRTId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XHImsApplyTablet::findFirst($iRTId);
            $type = $obj->iType;
            if ($obj->iState == 2 || $obj->iState == 3) {
                return $this->sendErrorResponse(500 , '该订单已经确认或已提交');
            }
            if ($type == 1 && !$iProdId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $hasRepeatedTchCode = array_unique(array_column($postData['tchBackInfo'] , 'prodId'));
            if(count($postData['tchBackInfo']) !== count($hasRepeatedTchCode)){
                return $this->sendErrorResponse(400 ,'有重复的平板类型');
            }
            $hasRepeated = array_unique(array_column($postData['shellCode'] ,'prodId'));
            if (count($postData['shellCode']) !== count($hasRepeated)) {
                return $this->sendErrorResponse(400, '有重复的平板壳');
            }
            $teachers = explode(',', $obj->sTeachers);
            $tabletNum = array_sum(array_column($postData['tchBackInfo'],'prodNum'));
            if (count($teachers) != $obj->iTchNum && $tabletNum != $tabletNum) {
                return $this->sendErrorResponse(500, '教师机数目与教师不符');
            }

            foreach ($postData['shellCode'] as $index =>$row){
                if(!$row['prodId'] || !$row['iNum']){
                    unset($postData['shellCode'][$index]);
                }
            }
            $postData['shellCode'] = array_values($postData['shellCode']);
            $obj->mTabletShell = $postData['shellCode'];
            $obj->mTchBackInfo = $postData['tchBackInfo'];
            if ($iProdId) { //学生机保存
                $obj->iProdId = $iProdId;
            }
            $obj->iState = 2;
            $obj->iChargeMode = Tool::getValue($postData, 'iChargeMode', 0);
            $obj->iSignState = 1; //等待签收
            if (!$obj->save()){
                $this->db->rollback();
                return $this->sendErrorResponse(500, '保存失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('确认成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

//    public function testAction(){
//        var_dump(XHImsApplyTablet::findFirst(29)->toArray());die;
//    }


}